#include "TEventThread.h"
#include "TRandom.h"
TEventThread::TEventThread(void)
{
	m_exit			 = false ;
	m_current_time	 = time(NULL);
	m_scheduler.initailize(1024);
}

TEventThread::~TEventThread(void)
{
}
void TEventThread::run( void * object ){
	m_current_time	 = time(NULL);
	printf("runing...\n");
	while ( !m_exit )
	{
#ifndef WIN32
		m_scheduler.run_event( 1000 );
		int tmp = time(NULL) - m_current_time ;
		if ( tmp < 0 || tmp >= 1 )
		{
			check_timeout();
			m_current_time	 = time(NULL);
		}
		
#else
		m_scheduler.run_once_event( 1000 );
		m_current_time = time(NULL);
#endif
	}
}
bool TEventThread::register_handler( TEventHandler * handler ){
	TAutoLock autolock(&m_lock );
	
	bool suc =  m_scheduler.register_handler( handler );
	if ( suc )
	{
#ifndef WIN32
		m_handles.push_back( handler );
#endif
		
	}
	return suc ;
}
void TEventThread::check_timeout(){
	//printf("check_timeout\n");
	TAutoLock autolock(&m_lock );
	std::vector< TEventHandler * >::iterator iter = m_handles.begin();
	TEventHandler * handler = NULL ;
	for ( ; iter != m_handles.end() ;)
	{
		handler	= *iter ;
		if ( handler->get_handle() == -1 )
		{
			iter  = m_handles.erase( iter );
		}
		else
		{
			handler->handle_timeout( handler ) ;
			iter ++ ;
		}
	}
}